package com.macbulldev.poc.testgin.controller;

import java.util.Date;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.macbulldev.poc.testgin.domain.AppUser;
import com.macbulldev.poc.testgin.domain.EventLog;
import com.macbulldev.poc.testgin.domain.Rate;
import com.macbulldev.poc.testgin.domain.Scenario;
import com.macbulldev.poc.testgin.domain.TrialGroup;
import com.macbulldev.poc.testgin.domain.Underwriter;
import com.macbulldev.poc.testgin.service.WebappUtils;


@org.springframework.roo.addon.web.mvc.controller.RooWebScaffold(path = "underwriter", automaticallyMaintainView = false, formBackingObject = com.macbulldev.poc.testgin.domain.Underwriter.class)
@org.springframework.web.bind.annotation.RequestMapping("/underwriter/**")
@org.springframework.stereotype.Controller
public class UnderwriterController {
	
	private static final Logger LOGGER = Logger.getLogger(Underwriter.class);
	
	@RequestMapping(value = "/underwriter/list", method = RequestMethod.GET)    
    public String renderUnderwriterList(@RequestParam(value = "pageNumber", required = false) Integer page, ModelMap modelMap) {    
		
		int sizeNo = 20;           
        int pageNumber= page == null ? 0 : page;
        
        modelMap.addAttribute("underwriters",Underwriter.findUnderwriterEntries(pageNumber*sizeNo, sizeNo));            
        Long count = Underwriter.countUnderwriters();
        modelMap.addAttribute("maxPageNumber", (Long)(count/sizeNo));
        
        
        LOGGER.debug("Undewrwriter List Size:  "+Underwriter.findUnderwriterEntries(pageNumber*sizeNo, sizeNo).size());
        LOGGER.debug("Undewrwriter Count:  "+count);
        
        return "underwriter/list";        
    }
	
	

	//HttpSession session =
	
	//AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
	
    
    @RequestMapping(value = "/underwriter", method = RequestMethod.POST)    
    public String create(@Valid Underwriter underwriter, BindingResult result, ModelMap modelMap,HttpSession session ) {    
        if (underwriter == null) throw new IllegalArgumentException("A underwriter is required");        
        
   
        
        if(Underwriter.findUnderwriterByDisplayNameAndImportName(underwriter.getDisplayName(), underwriter.getImportName()) != null)
        {
        	result.addError(new FieldError("underwriter","displayName","This Policy Type Already Exist and Duplicates Are Not Allowed"));
        }
        
        if (result.hasErrors()) {        
            modelMap.addAttribute("underwriter", underwriter);            
            modelMap.addAttribute("rates", Rate.findAllRates());            
            modelMap.addAttribute("scenarios", Scenario.findAllScenarios());            
            modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());            
            return "underwriter/create";            
        } 
        
        AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
        underwriter.setCreateUsername(sessionUser.getName());
    	underwriter.setUpdateUsername(sessionUser.getName());
    	underwriter.setCreateTs(new Date());
		underwriter.setUpdateTs(new Date());
		
		EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(Underwriter.class.getSimpleName());
    	log.setOperation("Underwriter "+ underwriter.getDisplayName()+" Created");
    	log.persist();
        
        
        underwriter.persist();        
        return "redirect:/underwriter/" + underwriter.getId();        
    }

	@RequestMapping(value = "/underwriter/form", method = RequestMethod.GET)    
    public String createForm(ModelMap modelMap) {    
        modelMap.addAttribute("underwriter", new Underwriter());        
        modelMap.addAttribute("rates", Rate.findAllRates());        
        modelMap.addAttribute("scenarios", Scenario.findAllScenarios());        
        modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());        
        return "underwriter/create";        
    }

	@RequestMapping(value = "/underwriter/{id}", method = RequestMethod.GET)    
    public String show(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("underwriter", Underwriter.findUnderwriter(id));        
        return "underwriter/show";        
    }

	@RequestMapping(value = "/underwriter", method = RequestMethod.GET)    
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, ModelMap modelMap) {    
        if (page != null || size != null) {        
            int sizeNo = size == null ? 10 : size.intValue();            
            modelMap.addAttribute("underwriters", Underwriter.findUnderwriterEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));            
            float nrOfPages = (float) Underwriter.countUnderwriters() / sizeNo;            
            modelMap.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));            
        } else {        
            modelMap.addAttribute("underwriters", Underwriter.findAllUnderwriters());            
        }        
        return "underwriter/list";        
    }

	@RequestMapping(method = RequestMethod.PUT)    
    public String update(@Valid Underwriter underwriter, BindingResult result, ModelMap modelMap,HttpSession session ) {    
        if (underwriter == null) throw new IllegalArgumentException("A underwriter is required");        
        if (result.hasErrors()) {        
            modelMap.addAttribute("underwriter", underwriter);            
            modelMap.addAttribute("rates", Rate.findAllRates());            
            modelMap.addAttribute("scenarios", Scenario.findAllScenarios());            
            modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());            
            return "underwriter/update";            
        }
        
        
        underwriter.setCreateUsername(Underwriter.findUnderwriter(underwriter.getId()).getCreateUsername());
        underwriter.setCreateTs(Underwriter.findUnderwriter(underwriter.getId()).getCreateTs());
        
        AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
        underwriter.setUpdateUsername(sessionUser.getName());
        underwriter.setUpdateTs(new Date());
        
        underwriter.merge();
        
        
        EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(Underwriter.class.getSimpleName());
    	log.setOperation("Underwriter "+ underwriter.getDisplayName()+" Updated");
    	log.persist();
        
        
        return "redirect:/underwriter/" + underwriter.getId();        
    }

	@RequestMapping(value = "/underwriter/{id}/form", method = RequestMethod.GET)    
    public String updateForm(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("underwriter", Underwriter.findUnderwriter(id));        
        modelMap.addAttribute("rates", Rate.findAllRates());        
        modelMap.addAttribute("scenarios", Scenario.findAllScenarios());        
        modelMap.addAttribute("trialgroups", TrialGroup.findAllTrialGroups());        
        return "underwriter/update";        
    }

	@RequestMapping(value = "/underwriter/{id}", method = RequestMethod.DELETE)    
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size,HttpSession session) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        
        AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
        
        EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(Underwriter.class.getSimpleName());
    	log.setOperation("Underwriter "+ Underwriter.findUnderwriter(id).getDisplayName()+" Created");
    	log.persist();
        
        Underwriter.findUnderwriter(id).remove(); 
        
        return "redirect:/underwriter?page=" + ((page == null) ? "1" : page.toString()) + "&size=" + ((size == null) ? "10" : size.toString());        
    }
}
